import {createSlice} from '@reduxjs/toolkit'
let use=JSON.parse(localStorage.getItem('use'))
let CarSplice=createSlice({
    name:'CarSplice',
    initialState:{
        cars:[]
    },
    reducers:{
        addCar(state,action){
            state.cars.push(action.payload)
        },
        setCars(state,action){
            state.cars=action.payload
        }
    }
})

export default CarSplice.reducers
export let {addCar,setCars} =CarSplice.actions

export const createWebSocket=()=>{
    const ws=new WebSocket(`ws://localhost:8080/?id=${use._id}`)
    ws.onopen=()=>{
        console.log('websocket连接成功')
    }
    ws.onmessage=(event)=>{
        // const data =JSON.parse(event.data)
        let data=JSON.parse(event.data)
        dispatch(setCars(data))
    }
    ws.onerror=(error)=>{
        console.log('websocket连接失败',error)
    }
    ws.onclose=()=>{
        console.log('websocket连接关闭')
    }
}